package com.smartum.mpr.client.event;

import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;

/**
 * Calls when {@link Window} was resized.
 * <p/>
 * Implements {@link ResizeHandler#onResize(com.google.gwt.event.logical.shared.ResizeEvent)} which fit panel to the
 * workbench size.
 */
public class WindowResizeHandler implements ResizeHandler {

    private final Widget widget;
    private final int heightParameter;
    private final int widthParameter;
    private final boolean isDependent;

    /**
     * Initialize all necessary parameters.
     *
     * @param widget          panel, which should be resized.
     * @param heightParameter this parameter show difference between workbench height and component height, dependent
     *                        from <code>isDependent</code> parameter
     * @param widthPrameter   this parameter show difference between workbench width and component width, dependent
     *                        from <code>isDependent</code> parameter
     * @param isDependent     when the value should taken away from the workbench
     */
    public WindowResizeHandler(Widget widget, int heightParameter, int widthPrameter, boolean isDependent) {
        this.widget = widget;
        this.heightParameter = heightParameter;
        this.widthParameter = widthPrameter;
        this.isDependent = isDependent;
    }

    public void onResize(ResizeEvent event) {

        int widthForResize;
        int heightForResize;
        if (!this.isDependent) {
            widthForResize = this.widthParameter != 0 ? this.widthParameter : Window.getClientWidth();
            heightForResize = this.heightParameter != 0 ? this.heightParameter : Window.getClientHeight();
        } else {
            widthForResize = Window.getClientWidth() - this.widthParameter;
            heightForResize = Window.getClientHeight() - this.heightParameter;
        }

        resizeWindow(heightForResize, widthForResize);
    }

    public void resizeWindow(int clientHeight, int clientWidth) {
        this.widget.setHeight(clientHeight + "px");
        this.widget.setWidth(clientWidth + "px");
    }
}
